package com.rme.main.api.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rme.common.core.api.BaseApiService;
import com.rme.common.core.api.BaseResponse;
import com.rme.common.core.utils.MD5Utils;
import com.rme.main.api.RegisterService;
import com.rme.main.api.impl.entity.SysUser;
import com.rme.main.api.impl.mapper.SysUserMapper;
import com.rme.main.util.SaltUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 周益和
 * @ClassName RegisterServiceImpl
 * @qq 1552951165
 */
@RestController
public class RegisterServiceImpl extends BaseApiService<String> implements RegisterService {
    @Autowired
    private SysUserMapper sysUserMapper;
    
    /**
     * 用户注册接口
     *
     * @param phoneNumber
     * @param password
     * @return
     */
    @Override
    public BaseResponse<String> register(String phoneNumber, String password) {
        // 1.验证参数是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            return setResultError("电话号码为空");
        }
        if (StringUtils.isEmpty(password)) {
            return setResultError("密码为空");
        }
        // 2.先根据手机号码 查数据判断是否已经存在该用户 如果不存在才可以注册 如果存在就无法注册
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("phone_number", phoneNumber);
        SysUser dbUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        if (dbUser != null) {
            return setResultError("该手机号码已经存在!");
        }
        // 3.加密密码 phoneNumber, password, UUID.randomUUID().toString().replace("-", "")
        String salt = SaltUtils.getSalt();
        String md5Password = MD5Utils.md5(password + salt);
        dbUser = new SysUser(phoneNumber, md5Password, salt);
        // 插入注册信息
        int result = sysUserMapper.insert(dbUser);
        return setResultDb(result);
    }
}
